package com.rent.collectrent.service.impl;

import com.rent.collectrent.dto.WriteOffRequest;
import com.rent.collectrent.dto.WriteOffResponse;
import com.rent.collectrent.entity.WriteOffSummary;
import com.rent.collectrent.mapper.WriteOffSummaryMapper;
import com.rent.collectrent.service.ProcessBankReceiptsService;
import com.rent.collectrent.service.RentWriteOffService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author news
 * *@date 2025/9/28
 */
@Service
@Slf4j
@Transactional
public class RentWriteOffServiceImpl implements RentWriteOffService {

    @Autowired
    private WriteOffSummaryMapper writeOffSummaryMapper;
    @Autowired
    private ProcessBankReceiptsService processBankReceiptsService;


    public CompletableFuture<WriteOffResponse> batchWriteOff(WriteOffRequest request) {
        String batchNo = "WO" + System.currentTimeMillis() + String.format("%04d", ThreadLocalRandom.current().nextInt(1000));
        long startTime = System.currentTimeMillis();
        try {
            log.info("开始批量核销，批次号: {}", batchNo);
            // 创建核销汇总记录
            WriteOffSummary summary = createWriteOffSummary(batchNo);
            processBankReceiptsService.processedBankReceiptsAsync(request, batchNo, summary, startTime);
            // 这里totalProcessed可以看逻辑给特异性值，表示还未执行完毕
            WriteOffResponse response = buildResponse(summary, 0);
            log.info("批量核销开始，批次号: {}", batchNo);
            return CompletableFuture.completedFuture(response);
        } catch (Exception e) {
            log.error("批量核销失败，批次号: {}", batchNo, e);
            return CompletableFuture.completedFuture(buildErrorResponse(e.getMessage(), batchNo));
        }
    }



    private WriteOffSummary createWriteOffSummary(String batchNo) {
        WriteOffSummary summary = new WriteOffSummary();
        summary.setBatchNo(batchNo);
        summary.setStatus("PROCESSING");
        summary.setStartTime(new Date());
        summary.setCreateTime(new Date());
        writeOffSummaryMapper.insert(summary);
        return summary;
    }



    private WriteOffResponse buildResponse(WriteOffSummary writeOffSummary, int totalProcessed) {
        return WriteOffResponse.builder()
                .batchNo(writeOffSummary.getBatchNo())
                .status(writeOffSummary.getStatus())
                .message("操作成功")
                .totalCount(totalProcessed)
                .totalPrincipal(writeOffSummary.getTotalPrincipal())
                .totalInterest(writeOffSummary.getTotalInterest())
                .totalAmount(writeOffSummary.getTotalAmount())
                .durationSeconds(writeOffSummary.getDurationSeconds())
                .build();
    }

    private WriteOffResponse buildErrorResponse(String message, String batchNo) {
        return WriteOffResponse.builder()
                .batchNo(batchNo)
                .status("ERROR")
                .message(message)
                .build();
    }

    public WriteOffResponse buildErrorResponse(String message) {
        return buildErrorResponse(message, null);
    }
}
